package com.collectplus.express.order;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.MainActivity;
import com.collectplus.express.R;
import com.collectplus.express.alipay.PayResult;
import com.collectplus.express.app.Intents;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.CouponBean;
import com.collectplus.express.model.OrderBean;
import com.collectplus.express.model.VisitDoorBackBean;
import com.collectplus.express.self.SelfOrderPayStampAdapter;
import com.collectplus.express.self.SelfOrderSubmitActivity;
import com.collectplus.express.view.HorizontalListView;
import com.collectplus.express.wxapi.WXPayEntryActivity;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.bhi.stamp.StampStoreActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import droid.frame.ui.dialog.AppDialog;
import droid.frame.umeng.UMeng;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.MathUtils;
import droid.frame.utils.lang.Str;
import droid.frame.utils.sqlite.DateUtils;

/**
 * 用户支付<br>
 * 收银台界面
 *
 * @author coffee<br>
 * 2015-6-16下午5:08:09
 */
public class OrderPayActivity extends BaseActivity2 implements OnClickListener {

    private final int SDK_PAY_FLAG = 1;
    private final int SDK_CHECK_FLAG = 2;

    //    private ListView mListView1; // 我的包裹
    private ListView mListView2; // 价格信息
    private ListView mListView3;//上门费用明细

    //    private ReceiverAdapter mAdapter1; // 收件人
    private OrderPriceAdapter mAdapter2;// 运费
    private OrderPriceVisitHomeAdapter mAdapter3;// 上门费
    private OrderBean order;
    private Serializable orderId;// int 或者String

    private TextView mStampName;// 邮票名称
    private TextView mStampHint;// 邮票剩余提示
    private TextView mCurrentStampNumTV;//当前可用邮票数量

    private CheckBox mStampCheckBox, mWxButton, mAliButton;
    private Button mOkButton;
    /**
     * 实际支付价格
     */
    private String mPayMoney;
    /**
     * 订单价格
     */
    private String mCost;
    private int mCouponsId;// 使用的邮票ID

    private String from;
    /**
     * 是否是补差价 1，是补差价
     */
    private int isCover;
    private ArrayList<CouponBean> stamps = null;

    private String stampOrderId = "";//新加使用邮票支付

    private boolean isRequest = false;//只有在当前activity处于后台时，才设置为true
    private boolean isWxFrom = false;//判断是不是微信支付之后取消的 true是微信支付返回来的  false不是微信支付返回来的
    private CouponBean couponBean = null;//用于保存当前点击的邮票对象
    private VisitDoorBackBean visitDoorBackBean = null;//如果上门取件的时候，visitDoorBackBean有值，显示上门费相关信息
    private boolean stampButtonCheck = false;//判断邮票是否选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // order = (OrderBean) getIntent().getSerializableExtra("item");
        from = getIntent().getStringExtra("from");
        isCover = getIntent().getIntExtra("isCover", 0);
        AppCache.setOrder(order);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.order_pay);
        super.findViewById();
        getAppTitle().setCommonTitle("收银台");
        //我的包裹列表暂时无用
        //        mListView1 = (ListView) findViewById(R.id.order_listview_1);
        mListView2 = (ListView) findViewById(R.id.order_listview_2);
        mListView3 = (ListView) findViewById(R.id.order_listview_3);

        // mCouponLayout = (LinearLayout) findViewById(R.id.pay_coupon_layout);
        // mCouponLayout.setOnClickListener(this);

        // mCouponTitle = (TextView) findViewById(R.id.pay_coupon_title);

        mStampName = (TextView) findViewById(R.id.stamp_name);
        mStampHint = (TextView) findViewById(R.id.stamp_hint);

        findViewById(R.id.pay_wx_layout).setOnClickListener(this);
        findViewById(R.id.pay_ali_layout).setOnClickListener(this);
        findViewById(R.id.pay_stamp_layout).setOnClickListener(this);
        mCurrentStampNumTV = (TextView) findViewById(R.id.currentstampnumTV);
        mStampCheckBox = (CheckBox) findViewById(R.id.pay_stamp_checkBox);
        mWxButton = (CheckBox) findViewById(R.id.pay_wx_checkBox);
        mAliButton = (CheckBox) findViewById(R.id.pay_ali_checkBox);
        mOkButton = (Button) findViewById(R.id.pay_ok_button);
        mOkButton.setOnClickListener(this);
        mStampCheckBox.setOnClickListener(this);

        // 如果订单不==null 则是从上一个界面传过来的-- 寄件主界面
        if (order != null) {
            orderId = order.getId();
            updateViewData();
        } else {
            orderId = getIntent().getSerializableExtra("orderId");
            if (orderId != null) {
                order = AppCache.getOrder();
                if (order != null) {
                    updateViewData(); // 先用缓存的数据
                }
                showLoadingDialog(null);
                AppHttp.getInstance().orderDetail(orderId);
                // AppHttp.getInstance().orderDetail(orderId + "");
            } else {
                showToast("订单id为空, 无法支付");
                super.finish();
            }
        }
        findViewById(getResources().getIdentifier("title_left_switcher", "id", getPackageName())).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                alterDialog();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 放在onResume是为了从邮票商城返回过来跟新数据
        if (isRequest && isWxFrom == false) {
            if (orderId != null) {
                showLoadingDialog(null);
                AppHttp.getInstance().orderDetail(orderId);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRequest = true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        orderId = intent.getSerializableExtra("orderId");
        if (orderId != null) {
            AppHttp.getInstance().orderDetail(orderId);
        }
    }

    private void alterDialog() {
        final AppDialog dialog = new AppDialog(this);
        dialog.setTitle("提示");
        if (Const.ParcelType.visitToHome == order.getParcelType()) {
            dialog.setContent("下单5分钟内未支付，订单将被取消哦，请尽快完成支付。");
        } else {
            dialog.setContent("下单1小时内未支付，订单将被取消哦，请尽快完成支付。");
        }
        dialog.setConfirmClickListener("继续支付", new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setCancelClickListener("确认离开", new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 如果是从下单界面进来的，则结束该界面的时候直接跳转到主页面
                if (SelfOrderSubmitActivity.class.getName().equals(from)) {
                    AppCache.setOrder(null);// 清空订单内容
                    AppCache.setParcelNew(null);
                    Intents.startMainActivityClearTop(getContext());
                }
                dialog.dismiss();
                OrderPayActivity.super.finish();
            }
        });
        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// 竖屏
            alterDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //选中邮票支付或取消邮票支付
            case R.id.pay_stamp_checkBox:
                if (order.getStampNum() > 0) {
                    if (couponBean == null) {
                        return;
                    }
                    //如果为普通邮票只能进行单选
                    if (!isNormalStamp(couponBean.getStampType())) {//如果为正常邮票
                        if (!stampButtonCheck) {
                            //如果是上门,如果是限免
                            if (!isVisitHomeParcel()) {
                                stampButtonCheck = true;
                                mStampCheckBox.setChecked(true);
                                mAliButton.setChecked(false);
                                mWxButton.setChecked(false);
                                mOkButton.setText("确认邮票支付");
                                OrderBean newOrder = new OrderBean();
                                newOrder.setCost("0.00");
                                newOrder.setIsCover(order.getIsCover());
                                mAdapter2 = new OrderPriceAdapter(newOrder, this);
                                mListView2.setAdapter(mAdapter2);
                            } else {
                                //不是限免的，说明需要支付金额
                                stampButtonCheck = true;
                                mStampCheckBox.setChecked(true);
                                if (!mWxButton.isChecked()) {
                                    mAliButton.setChecked(true);
                                }
                                mPayMoney = visitDoorBackBean.getPrice();
                                mOkButton.setText("需要支付" + visitDoorBackBean.getPrice() + "元");

                                OrderBean newOrder = new OrderBean();
                                newOrder.setCost("0.00");
                                newOrder.setIsCover(order.getIsCover());
                                mAdapter2 = new OrderPriceAdapter(newOrder, this);
                                mListView2.setAdapter(mAdapter2);
                            }
                        } else {//取消使用邮票
                            OrderBean newOrder = new OrderBean();
                            //如果是上门,如果是限免
                            if (!isVisitHomeParcel()) {
                                stampButtonCheck = false;
                                mStampCheckBox.setChecked(false);
                                if (!mWxButton.isChecked()) {
                                    mAliButton.setChecked(true);
                                }
                                mPayMoney = order.getCost();
                                mOkButton.setText("需要支付" + order.getCost() + "元");
                                newOrder.setCost(order.getCost());
                                newOrder.setIsCover(order.getIsCover());
                            } else {
                                //不是限免的，说明需要支付金额
                                stampButtonCheck = false;
                                mStampCheckBox.setChecked(false);
                                if (!mWxButton.isChecked()) {
                                    mAliButton.setChecked(true);
                                }
                                mPayMoney = MathUtils.add(visitDoorBackBean.getPrice(), order.getCost()) + "";
                                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), order.getCost()) + "元");
                                newOrder.setCost(order.getCost());
                                newOrder.setIsCover(order.getIsCover());
                            }
                            mAdapter2 = new OrderPriceAdapter(newOrder, this);
                            mListView2.setAdapter(mAdapter2);
                        }
                    } else {//打折邮票
                        OrderBean newOrder = new OrderBean();
                        newOrder.setIsCover(order.getIsCover());
                        if (mStampCheckBox.isChecked()) {//选中邮票
                            stampButtonCheck = true;
                            mStampCheckBox.setChecked(true);
                            if (!mWxButton.isChecked()) {
                                mAliButton.setChecked(true);
                            }
                            double price = computePrice(couponBean.getStampType());
                            newOrder.setCost((price <= 0 ? 0.01 : price) + "");
                            //限免
                            if (!isVisitHomeParcel()) {
                                mPayMoney = newOrder.getCost();
                                mOkButton.setText("需要支付" + newOrder.getCost() + "元");
                            } else {
                                mPayMoney = MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "";
                                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "元");
                            }
                            mAdapter2 = new OrderPriceAdapter(newOrder, getContext());
                            mListView2.setAdapter(mAdapter2);
                        } else {//取消选中邮票
                            newOrder.setCost(order.getCost());
                            if (!mWxButton.isChecked()) {
                                mAliButton.setChecked(true);
                            }
                            //限免
                            if (!isVisitHomeParcel()) {
                                mPayMoney = newOrder.getCost();
                                mOkButton.setText("需要支付" + newOrder.getCost() + "元");
                            } else {
                                mPayMoney = MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "";
                                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "元");
                            }
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(false);
                            mAdapter2 = new OrderPriceAdapter(order, getContext());
                            mListView2.setAdapter(mAdapter2);
                        }
                    }
                }
                break;
            case R.id.pay_wx_layout:
                //普通邮票
                if (couponBean == null || !isNormalStamp(couponBean.getStampType())) {
                    String serviceCose1 = order.getServiceCost();
                    String totalCost1 = MathUtils.add(serviceCose1, order.getCost()) + "";
                    OrderBean newOrder = new OrderBean();
                    newOrder.setIsCover(order.getIsCover());
                    if (stampButtonCheck) {
                        newOrder.setCost("0.00");
                    } else {
                        newOrder.setCost(order.getCost());
                    }
                    //限免
                    if (!isVisitHomeParcel()) {
                        mAliButton.setChecked(false);
                        mWxButton.setChecked(true);
                        mStampCheckBox.setChecked(false);
                        stampButtonCheck = false;
                        mOkButton.setText("需要支付" + Str.formatPrice(totalCost1) + "元");
                    } else {
                        mAliButton.setChecked(false);
                        mWxButton.setChecked(true);
                        //没有使用邮票支付
                        if (!stampButtonCheck) {
                            mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), totalCost1) + "元");
                        } else {
                            mOkButton.setText("需要支付" + Str.formatPrice(visitDoorBackBean.getPrice()) + "元");
                        }
                    }
                    mAdapter2 = new OrderPriceAdapter(newOrder, this);
                    mListView2.setAdapter(mAdapter2);
                } else {//折扣邮票
                    mAliButton.setChecked(false);
                    mWxButton.setChecked(true);
                }
                break;
            case R.id.pay_ali_layout:
                if (couponBean == null || !isNormalStamp(couponBean.getStampType())) {
                    String serviceCose = order.getServiceCost();
                    String totalCost = MathUtils.add(serviceCose, order.getCost()) + "";
                    OrderBean newOrder = new OrderBean();
                    newOrder.setIsCover(order.getIsCover());
                    if (stampButtonCheck) {
                        newOrder.setCost("0.00");
                    } else {
                        newOrder.setCost(order.getCost());
                    }
                    //限免
                    if (!isVisitHomeParcel()) {
                        stampButtonCheck = false;
                        mStampCheckBox.setChecked(false);
                        mAliButton.setChecked(true);
                        mWxButton.setChecked(false);
                        mOkButton.setText("需要支付" + Str.formatPrice(totalCost) + "元");
                    } else {
                        mAliButton.setChecked(true);
                        mWxButton.setChecked(false);
                        if (!stampButtonCheck) {
                            mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), totalCost) + "元");
                        } else {
                            mOkButton.setText("需要支付" + Str.formatPrice(visitDoorBackBean.getPrice()) + "元");
                        }
                    }
                    mAdapter2 = new OrderPriceAdapter(newOrder, this);
                    mListView2.setAdapter(mAdapter2);
                } else {
                    mAliButton.setChecked(true);
                    mWxButton.setChecked(false);
                }
                break;
            // 邮票支付
            case R.id.pay_stamp_layout:
                if (order.getStampNum() > 0) {
                    popupWindowView();
                } else {
                    Intent intent = new Intent(this, StampStoreActivity.class);
                    intent.putExtra("from", 1);
                    startActivityForResult(intent, 101);
                }
                break;
            // 支付、提交订单
            case R.id.pay_ok_button:
                UMeng.click(getContext(), "self_order_pay_click");
                payMoney();
                break;
            // 选取邮票
//            case R.id.pay_coupon_layout:
//                if (mCost == null) {
//                    // 设置按钮不可点击
//                    // mOkButton.setEnabled(false);
//                } else {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), CouponListActivity.class);
//                    intent.putExtra("couponId", mCouponsId);
//                    intent.putExtra("cost", mCost);
//                    intent.putExtra("from", "pay");
//                    startActivityForResult(intent, 100);
//                }

//                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 100) {
            CouponBean coupon = (CouponBean) data.getSerializableExtra("item");
            updateCoupon(coupon);
        } else if (requestCode == 101) {

        }
    }

    private SimpleDateFormat sdf;

    /**
     * 注意 如果是没报价之前，首次进来 order.getCost == null;
     */
    private void updateViewData() {

        //        ArrayList<ReceiverBean> receivers = order.getReceivers();
        //我的包裹适配器暂时不用
        //        mAdapter1 = new ReceiverAdapter(receivers, getContext(), mListView1);
        //        mListView1.setAdapter(mAdapter1);
        // 不显示label "包裹信息"
        //        if (mAdapter1.isEmpty()) {
        //            findViewById(R.id.order_listview1_label).setVisibility(View.GONE);
        //        }
        mAdapter2 = new OrderPriceAdapter(order, getContext());
        mListView2.setAdapter(mAdapter2);
        mCost = order.getCost();
        if (Const.ParcelType.visitToHome == order.getParcelType()) {
            mAdapter3 = new OrderPriceVisitHomeAdapter(order, getContext());
            mListView3.setAdapter(mAdapter3);
        }
        //
        List<CouponBean> couponList = order.getCoupons();
        if (couponList != null && couponList.size() > 0) {
            CouponBean coupon = couponList.get(0);
            // mCouponLayout.setOnClickListener(this);
            updateCoupon(coupon);
        } else {
            // mCouponLayout.setVisibility(View.VISIBLE);
            // mCouponLayout.setOnClickListener(null);
            // mCouponTitle.setText("暂无可用的邮票");
            String serviceCose = order.getServiceCost();
            String totalCost = MathUtils.add(serviceCose, order.getCost()) + "";
            //            mOkButton.setText("需要支付" + Str.formatPrice(totalCost) + "元");
            //限免
            if (!isVisitHomeParcel()) {
                mOkButton.setText("需要支付" + Str.formatPrice(totalCost) + "元");
            } else {
                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), totalCost) + "元");
            }
            mPayMoney = totalCost;
            AppCache.getOrder().setPayMoney(mPayMoney + "");
        }

        if (order.getIsCover() == 0) {
            if (order.getStampNum() > 0 && stamps != null && stamps.size() > 0) {
                mCurrentStampNumTV.setVisibility(View.VISIBLE);
                mStampCheckBox.setVisibility(View.VISIBLE);
                mStampHint.setVisibility(View.GONE);
                if (couponBean == null) {
                    couponBean = stamps.get(0);
                }
                mStampName.setText(couponBean.getStampName());
                stampOrderId = couponBean.getStampOrderId();
                int couponNum = 0;
                for (CouponBean couponBean : stamps) {
                    couponNum += Integer.valueOf(couponBean.getStampNum());
                }
                mCurrentStampNumTV.setText("点击可选,共" + couponNum + "张");
                //判断是否为折扣邮票，如果是折扣邮票，默认选中支付宝支付
                OrderBean newOrder = new OrderBean();
                //折扣邮票
                if (isNormalStamp(couponBean.getStampType())) {
                    if (!mWxButton.isChecked()) {
                        mAliButton.setChecked(true);
                    }
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    double price = computePrice(couponBean.getStampType());
                    newOrder.setCost((price <= 0 ? 0.01 : price) + "");
                    mPayMoney = newOrder.getCost();
                    //                    mOkButton.setText("需要支付" + newOrder.getCost() + "元");
                    //限免
                    if (!isVisitHomeParcel()) {
                        mOkButton.setText("需要支付" + newOrder.getCost() + "元");
                    } else {
                        mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "元");
                    }
                } else {//普通邮票
                    //如果不是限免
                    if (isVisitHomeParcel()) {
                        if (!mWxButton.isChecked()) {
                            mAliButton.setChecked(true);
                        }
                        stampButtonCheck = true;
                        mStampCheckBox.setChecked(true);
                    } else {
                        if (mAliButton.isChecked()) {
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(true);
                            mAliButton.setChecked(false);
                            mWxButton.setChecked(false);
                        } else if (mWxButton.isChecked()) {
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(true);
                            mAliButton.setChecked(false);
                            mWxButton.setChecked(false);
                        } else {
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(true);
                            mAliButton.setChecked(false);
                            mWxButton.setChecked(false);
                        }
                    }
                    newOrder.setCost("0.00");
                    //限免
                    if (!isVisitHomeParcel()) {
                        mOkButton.setText("确认邮票支付");
                    } else {
                        mOkButton.setText("需要支付" + visitDoorBackBean.getPrice() + "元");
                    }
                    //                    mOkButton.setText("确认邮票支付");
                }
                mAdapter2 = new OrderPriceAdapter(newOrder, this);
                mListView2.setAdapter(mAdapter2);
            } else {
                //
                if (mWxButton.isChecked()) {
                    stampButtonCheck = false;
                    mStampCheckBox.setChecked(false);
                    mAliButton.setChecked(false);
                    mWxButton.setChecked(true);
                } else {
                    stampButtonCheck = false;
                    mStampCheckBox.setChecked(false);
                    mAliButton.setChecked(true);
                    mWxButton.setChecked(false);
                }
                mCurrentStampNumTV.setVisibility(View.GONE);
            }
        } else {
            findViewById(R.id.pay_stamp_layout).setVisibility(View.GONE);
        }
    }

    private void updateCoupon(CouponBean coupon) {
        mCouponsId = coupon.getId();
        if (sdf == null) {
            sdf = DateUtils.getDateFormat("yyyy-MM-dd");
        }
        // 设置邮票
        mAdapter2.setCoupon(coupon);

        String serviceCose = order.getServiceCost();
        String totalCost = MathUtils.add(serviceCose, order.getCost()) + "";
        String cheap = coupon.getCheapValue();

        // 首单-30 || 立减
        if (coupon.getType() <= 2) {
            mPayMoney = MathUtils.sub(totalCost, cheap) + "";
        } else if (coupon.getType() == 3) {
            // 符合满减条件
            if (MathUtils.sub(totalCost, coupon.getConditionValue()) >= 0) {
                mPayMoney = MathUtils.sub(totalCost, cheap) + "";
            }
        }

        if (Str.parseFloat(mPayMoney) > 0) {
            mPayMoney = Str.formatPrice(mPayMoney);
            //限免
            if (!isVisitHomeParcel()) {
                mOkButton.setText("需要支付" + mPayMoney + "元");
            } else {
                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), mPayMoney) + "元");
            }
            //            mOkButton.setText("需要支付" + mPayMoney + "元");
        } else {
            String money = "0.01";
            //限免
            if (!isVisitHomeParcel()) {
                mOkButton.setText("需要支付0.01元");
                mPayMoney = money;
            } else {
                mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), money) + "元");
                mPayMoney = MathUtils.add(visitDoorBackBean.getPrice(), money) + "";
            }
        }
        if (AppCache.getOrder() != null) {
            AppCache.getOrder().setPayMoney(mPayMoney + "");
        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 取消订单  未发现有使用的
            case MsgID.order_cancel:
                cancelLoadingDialog();
                AppResult<?> result1 = JSON.parser(msg.obj);
                switch (result1.getStatus()) {
                    case 1:
                        AppCache.removeOrderAlls();
                        // Cache.setLocationItems(null);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent();
                                intent.setClass(getContext(), MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                OrderPayActivity.super.finish();// 关闭当前Activity
                            }
                        });
                        break;
                    default:
                        showToast(result1.getMessage());
                        break;
                }
                return true;
            case MsgID.order_detail:
                cancelLoadingDialog();
                final AppResult<OrderBean> result = JSON.parser(msg.obj.toString(), OrderBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            order = result.getResult();
                            if (order == null) {
                                showToast("获取订单数据失败");
                                finish();
                                return;
                            }
                            order.setIsCover(isCover);
                            stamps = order.getStamps();
                            visitDoorBackBean = order.getResultObject();
                            // 如果订单已支付
                            if (order.getStatus() == Const.OrderStatus.payed) {
                                AppCache.removeOrderAlls();
                                Intent intent = new Intent();
                                intent.setClass(getContext(), MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                finish();
                            } else {
                                AppCache.setOrder(order);
                                AppCache.setOrderId(order.getOrderId());
                                updateViewData();
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            //微信支付
            case MsgID.weiXinPay:
                cancelLoadingDialog();
                final AppResult<WxPayModel> wxResult = JSON.parser(msg.obj.toString(), WxPayModel.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (wxResult == null) {
                            showToast("服务器异常");
                            return;
                        }
                        if (wxResult.isSuccess()) {
                            WxPayModel wxModel = wxResult.getResult();
                            if (wxModel == null) {
                                showToast("服务器异常");
                                return;
                            }
                            com.shb.model.OrderPayBean pay = new com.shb.model.OrderPayBean(wxModel);
                            handleWxpay(pay);
                            isWxFrom = true;
                            isRequest = false;
                        } else {
                            showToast(wxResult.getMessage());
                        }
                    }
                });
                return true;
            //邮票支付
            case MsgID.stamp_pay:
                cancelLoadingDialog();
                AppResult<?> stampResult = JSON.parser(msg.obj.toString());
                if (stampResult != null && stampResult.isSuccess()) {
                    showToast("支付成功");
                    AppLogic.getInstance().onPaySuccess(getContext());
                    OrderPayActivity.super.finish();
                }
                return false;
            //支付宝支付
            case MsgID.aliPay:
                cancelLoadingDialog();
                final AppResult<?> aliResult = JSON.parser(msg.obj.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (aliResult.getResult() == null) {
                            showToast("服务器异常");
                            return;
                        }
                        if (aliResult.isSuccess()) {
                            alipay(aliResult.getResult().toString());
                            isRequest = false;
                            isWxFrom = false;
                        } else {
                            showToast(aliResult.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 处理跳转到微信支付
     *
     * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        couponBean = null;
                        Toast.makeText(OrderPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        // startActivity(new Intent(OrderPayActivity.this, OrderEvaluateActivity.class));
                        AppHttp.getInstance().orderPayCallBack(order.getOrderId(), 2, order.getIsCover());
                        AppLogic.getInstance().onPaySuccess(getContext());
                        OrderPayActivity.super.finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(OrderPayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(OrderPayActivity.this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(OrderPayActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付方法
     */
    public void payMoney() {
        if (mAliButton.isChecked()) {
            UMeng.click(getContext(), "orderpay_alipay_click");
            showLoadingDialog(null);
            //如果是折扣邮票，给后台传stampOrderId，否则不传
            if (Const.ParcelType.visitToHome == order.getParcelType()) {
                if (couponBean != null && mStampCheckBox.isChecked()) {
                    AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, Integer.parseInt(stampOrderId), order.getIsCover());
                } else {
                    AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, mCouponsId, order.getIsCover());
                }
            } else {
                if (couponBean != null && isNormalStamp(couponBean.getStampType()) && mStampCheckBox.isChecked()) {
                    AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, Integer.parseInt(stampOrderId), order.getIsCover());
                } else {
                    AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, mCouponsId, order.getIsCover());
                }
            }
            //            if (couponBean != null && isNormalStamp(couponBean.getStampType()) && mStampCheckBox.isChecked()) {
            //                AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, Integer.parseInt(stampOrderId), order.getIsCover());
            //            } else {
            //                AppHttp.getInstance().aliPay(order.getOrderId(), mPayMoney, mCost, mCouponsId, order.getIsCover());
            //            }
        } else if (mWxButton.isChecked()) {
            final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
            if (wxapi.isWXAppInstalled() == false) {
                showToast("未安装微信");
                return;
            }
            UMeng.click(getContext(), "orderpay_wxpay_click");
            showLoadingDialog(null);
            WXPayEntryActivity.payFrom = 0;
            //如果是折扣邮票，给后台传stampOrderId，否则不传
            if (Const.ParcelType.visitToHome == order.getParcelType()) {
                if (couponBean != null && mStampCheckBox.isChecked()) {
                    AppHttp.getInstance().weiXinPay(order.getOrderId(), mPayMoney, mCost, Integer.parseInt(stampOrderId), order.getIsCover());
                } else {
                    AppHttp.getInstance().weiXinPay(order.getOrderId(), mPayMoney, mCost, mCouponsId, order.getIsCover());
                }
            } else {
                if (couponBean != null && isNormalStamp(couponBean.getStampType()) && mStampCheckBox.isChecked()) {
                    AppHttp.getInstance().weiXinPay(order.getOrderId(), mPayMoney, mCost, Integer.parseInt(stampOrderId), order.getIsCover());
                } else {
                    AppHttp.getInstance().weiXinPay(order.getOrderId(), mPayMoney, mCost, mCouponsId, order.getIsCover());
                }
            }
        } else if (mStampCheckBox.isChecked() && !isVisitHomeParcel()) {//如果是限免的才可以使用邮票支付
            if (isEmpty(stampOrderId)) {
                return;
            }
            UMeng.click(getContext(), "orderpay_stamp_click");
            isWxFrom = false;
            showLoadingDialog(null);
            AppHttp.getInstance().stampPay(order.getOrderId(), stampOrderId);
        } else {
            showToast("请选择支付方式");
        }
    }

    /**
     * 选择可用邮票
     * 更新popupwindow状态和显示
     */
    @SuppressLint("WrongConstant")
    private void popupWindowView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.self_orderpay_choose_stamp, null);
        final PopupWindow popupWindow = DialogMgr.createPopupWindow(getContext(), view);
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.showAtLocation(mOkButton, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        HorizontalListView horizontalListView = (HorizontalListView) view.findViewById(R.id.horizontal_lv);
        final SelfOrderPayStampAdapter adapter = new SelfOrderPayStampAdapter(stamps, getContext(), horizontalListView);
        horizontalListView.setAdapter(adapter);
        //关闭按钮
        ImageView closeIV = (ImageView) view.findViewById(R.id.title_right);
        closeIV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        horizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CouponBean bean = adapter.getItem(position);
                if (bean == null) {
                    return;
                }
                couponBean = bean;
                OrderBean newOrder = new OrderBean();
                newOrder.setIsCover(order.getIsCover());
                //折扣邮票
                if (isNormalStamp(couponBean.getStampType())) {
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    if (!mWxButton.isChecked()) {
                        mAliButton.setChecked(true);
                    }
                    double price = computePrice(couponBean.getStampType());
                    newOrder.setCost((price <= 0 ? 0.01 : price) + "");
                    mPayMoney = newOrder.getCost();
                    //限免
                    if (!isVisitHomeParcel()) {
                        mOkButton.setText("需要支付" + newOrder.getCost() + "元");
                    } else {
                        mOkButton.setText("需要支付" + MathUtils.add(visitDoorBackBean.getPrice(), newOrder.getCost()) + "元");
                    }
                } else {//普通邮票
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    //限免
                    if (!isVisitHomeParcel()) {
                        mAliButton.setChecked(false);
                        mWxButton.setChecked(false);
                        mOkButton.setText("确认邮票支付");
                    } else {
                        if (!mWxButton.isChecked()) {
                            mAliButton.setChecked(true);
                        }
                        mPayMoney = visitDoorBackBean.getPrice();
                        mOkButton.setText("需要支付" + visitDoorBackBean.getPrice() + "元");
                    }
                    newOrder.setCost("0.00");
                }
                stampOrderId = couponBean.getStampOrderId();
                mStampName.setText(couponBean.getStampName());
                mAdapter2 = new OrderPriceAdapter(newOrder, getContext());
                mListView2.setAdapter(mAdapter2);
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 判断是否为普通邮票
     *
     * @param stampType >=11&&<20 属于折扣  >=21属于优惠券
     * @return true 折扣邮票  false 普通邮票
     */
    private boolean isNormalStamp(int stampType) {
        if (stampType >= 11) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否是上门取件，如果是上门取件，并且是限免，返回false，其他情况都返回true
     * 1 限免
     *
     * @return
     */
    private boolean isVisitHomeParcel() {
        if (Const.ParcelType.visitToHome == order.getParcelType() && null != visitDoorBackBean && 1 != visitDoorBackBean.getDiscountType()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 计算价钱，折扣邮票用相乘，优惠卷相减
     *
     * @param stampType
     * @return
     */
    private double computePrice(int stampType) {
        if (stampType >= 11 && stampType < 20) {
            return MathUtils.round(MathUtils.mul(Double.parseDouble(order.getCost()), couponBean.getStampValue()), 2);
        } else if (stampType >= 21 && stampType < 30) {
            return MathUtils.round(MathUtils.sub(Double.parseDouble(order.getCost()), couponBean.getStampValue()), 2);
        }
        return 0.00;
    }

    @Override
    protected void onDestroy() {
        //我的包裹暂时没用
        //        mListView1.setAdapter(null);
        mListView2.setAdapter(null);
        couponBean = null;
        super.onDestroy();
        Log.d("11111", "orderpayactivity onDestroy()");
    }

}
